package com.sparrow.common.ai.behaviortree;

import com.sparrow.common.ai.behaviortree.monitor.BTMonitor;
import com.sparrow.common.ai.behaviortree.task.BehaviorTask;

import java.util.HashMap;
import java.util.Map;

/**
 * 行为树上下文
 */
public class BehaviorContext {
    /**
     * 行为树 根节点任务
     */
    private BehaviorTask rootTask;
    /**
     * 行为树运行时数据
     */
    private final Map<String, Object> data = new HashMap<>();
    private Object owner;

    private BTMonitor monitor;

    public BTMonitor getMonitor() {
        return monitor;
    }

    public void setMonitor(BTMonitor monitor) {
        this.monitor = monitor;
    }

    public void setRootTask(BehaviorTask rootTask) {
        this.rootTask = rootTask;
    }

    public BehaviorTask getRootTask() {
        return rootTask;
    }

    public <T> void put(String key, T value) {
        data.put(key, value);
    }

    public <T> T get(String key, Class<T> clazz) {
        Object value = data.get(key);
        return clazz.isInstance(value) ? clazz.cast(value) : null;
    }

    public <T> T getOr(String key, Class<T> clazz, T def) {
        Object value = data.get(key);
        return clazz.isInstance(value) ? clazz.cast(value) : def;
    }

    public boolean has(String key) {
        return data.containsKey(key);
    }

    public void setOwner(Object owner) {
        this.owner = owner;
    }

    @SuppressWarnings("unchecked")
    public <T> T getOwner() {
        if (owner == null) {
            return null;
        }
        return (T) owner;
    }

    public boolean remove(String key) {
        return data.remove(key) != null;
    }
}
